<?php


namespace app\utils;

use AlibabaCloud\Darabonba\Stream\StreamUtil;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeBasicRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeChinesePassportRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeExitEntryPermitToHKRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeExitEntryPermitToMainlandRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizePassportRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

use app\lib\exception\OutsideApiException;
use Darabonba\OpenApi\Models\Config;
use Exception;
use think\facade\Filesystem;
use think\facade\Log;

class AliyunUtils
{
    private $p = 'Aliyun';

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocrapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }
    private function log($text, $type){
                    Log::channel('card')->info($type.'>>'.$text);
    }

    public function saveFile($uploadFile,$saveClass){
        $saveName = Filesystem::disk('local')->putFile('card/'.$saveClass, $uploadFile);
        $path = Filesystem::disk('local')->path($saveName);
        return $path;
    }

    public function getIDCard($uploadFile){
        $saveFile = $this->saveFile($uploadFile, 'IDcard');
        $bodyStream = StreamUtil::readFromFilePath($saveFile);

        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizeBasicRequest = new RecognizeBasicRequest([
            "outputFigure" => true,
            "body" => $bodyStream,
            "outputQualityInfo" => true
        ]);

        $result = [

        ];
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->recognizeBasicWithOptions($recognizeBasicRequest, new RuntimeOptions([]));
            $resultArr = json_decode($response->body->data, true);
            $this->log($resultArr['content'], 'NI');
            if (preg_match('/姓\s*名(.*)性\s*别(.*)民\s*族.*出\s*生(.*)住\s*址(.*)公民身份号码(.*)/', $resultArr['content'], $infoArr)){
                $result = [
                    'second_name' => '',
                    'card_expiration' => '',
                    'nationality' => '',
                    'card_type' => 'NI',
                    'country_code' => '',
                    'name' => preg_replace('/\s/', '', $infoArr[1]??''),
                    'sex' => preg_replace('/\s/', '', $infoArr[2]??''),
                    'birthday' =>substr(preg_replace('/\D/','-',$infoArr[3]),0,-1),
                    'address' => preg_replace('/\s/', '', $infoArr[4]??''),
                    'id_card' => preg_replace('/\s/', '', $infoArr[5]??''),
                ];
            }else{
                $result = $resultArr['content'];
            }

        } catch (Exception $error) {
           throw new OutsideApiException($error->getMessage(), $this->p);
        }




        return $result;
    }

    public function getPASSPORT1($uploadFile){
        $saveFile = $this->saveFile($uploadFile, 'P');
        $bodyStream = StreamUtil::readFromFilePath($saveFile);

        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizePassportRequest = new RecognizePassportRequest([
            "body" => $bodyStream
        ]);

        $runtime = new RuntimeOptions([]);
        $result = [

        ];
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->recognizePassportWithOptions($recognizePassportRequest, $runtime);
            $resultArr = json_decode($response->body->data, true);
            $this->log( json_encode($resultArr['data'],JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ,'P1');


            $result = [
                'name' => $resultArr['data']['name'],
                'card_expiration' =>substr(preg_replace('/\D+/','-',$resultArr['data']['validToDate']),0,-1),
                'nationality' => $resultArr['data']['nationality'],
                'card_type' => 'P',
                'country_code' => $resultArr['data']['country'],
                'second_name' =>  $resultArr['data']['nameEn'],
                'sex' =>  preg_match('/M/', $resultArr['data']['sex'])  ? '男': '女',
                'birthday' =>  substr(preg_replace('/\D+/','-',$resultArr['data']['birthDateYmd']),0,-1),
                'address' => '',
                'id_card' => $resultArr['data']['passportNumber'],
                ];

        } catch (Exception $error) {
            throw new OutsideApiException($error->getMessage(), $this->p);
        }
        return $result;
    }


    public function getPASSPORT2($uploadFile){
        $saveFile = $this->saveFile($uploadFile, 'P');
        $bodyStream = StreamUtil::readFromFilePath($saveFile);
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizeChinesePassportRequest = new RecognizeChinesePassportRequest([
            "outputFigure" => true,
            "body" => $bodyStream
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->recognizeChinesePassportWithOptions($recognizeChinesePassportRequest, $runtime);
            $resultArr = json_decode($response->body->data, true);

            $this->log( json_encode($resultArr['data'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ,'P2');


            $result = [
                'name' => $resultArr['data']['name'],
                'card_expiration' => preg_replace('/\D+/','-',$resultArr['data']['validToDate']),
                'nationality' => $resultArr['data']['nationality'],
                'card_type' => 'P',
                'country_code' => $resultArr['data']['countryCode'],
                'second_name' =>  $resultArr['data']['nameEn'],
                'sex' =>  preg_match('/M/', $resultArr['data']['sex'])  ? '男': '女',
                'birthday' =>  preg_replace('/\D+/','-',$resultArr['data']['birthDate']),
                'address' => '',
                'id_card' => $resultArr['data']['passportNumber'],
            ];


        } catch (Exception $error) {
            throw new OutsideApiException($error->getMessage(), $this->p);
        }
        return $result;
    }
    public function getExitEntry($uploadFile){
        $saveFile = $this->saveFile($uploadFile, 'P');
        $bodyStream = StreamUtil::readFromFilePath($saveFile);
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizeExitEntryPermitToMainlandRequest = new RecognizeExitEntryPermitToMainlandRequest([
            "body" => $bodyStream,
            "outputFigure" => true
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->recognizeExitEntryPermitToMainlandWithOptions($recognizeExitEntryPermitToMainlandRequest, $runtime);
            $resultArr = json_decode($response->body->data, true);

            $this->log( json_encode($resultArr['data'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ,'P2');

//2020.04.15-2030.04.14
            $rangArr = explode('-', $resultArr['data']['validPeriod']);

            $result = [
                'name' => $resultArr['data']['nameCn'],
                'card_expiration' => preg_replace('/\D+/','-',$rangArr[1]),
                'nationality' => 'CN',
                'card_type' => 'A',
                'country_code' => 'CN',
                'second_name' =>  $resultArr['data']['nameEn'],
                'sex' =>  $resultArr['data']['sex'],
                'birthday' =>  preg_replace('/\D+/','-',$resultArr['data']['birthDate']),
                'address' => '',
                'id_card' => $resultArr['data']['permitNumber'],
            ];


        } catch (Exception $error) {
            throw new OutsideApiException($error->getMessage(), $this->p);
        }
        return $result;
    }

    public function getPermitToHK($uploadFile){
        $saveFile = $this->saveFile($uploadFile, 'P');
        $bodyStream = StreamUtil::readFromFilePath($saveFile);
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizeExitEntryPermitToHKRequest = new RecognizeExitEntryPermitToHKRequest([
            "body" => $bodyStream,
            "outputFigure" => true
        ]);
        $runtime = new RuntimeOptions([]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            $response =  $client->recognizeExitEntryPermitToHKWithOptions($recognizeExitEntryPermitToHKRequest, $runtime);
            $resultArr = json_decode($response->body->data, true);

            $this->log( json_encode($resultArr['data'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ,'P2');

//2020.04.15-2030.04.14
            $rangArr = explode('-', $resultArr['data']['validPeriod']);

            $result = [
                'name' => $resultArr['data']['nameCn'],
                'card_expiration' => preg_replace('/\D+/','-',$rangArr[1]),
                'nationality' => 'CN',
                'card_type' => 'P',
                'country_code' => 'CN',
                'second_name' =>  $resultArr['data']['nameEn'],
                'sex' =>  $resultArr['data']['sex'],
                'birthday' =>  preg_replace('/\D+/','-',$resultArr['data']['birthDate']),
                'address' => '',
                'id_card' => $resultArr['data']['permitNumber'],
            ];


        } catch (Exception $error) {
            throw new OutsideApiException($error->getMessage(), $this->p);
        }
        return $result;
    }



}